問題描述
Kivy:如何使用 RecycleView 在 Kivy 中顯示具有可變行的列表? (Kivy: how to display a list with variable rows in Kivy with a RecycleView?)
我是 Python 和 Kivy 的新手,我需要顯示一個包含可變行的列表,我正在嘗試使用回收視圖,但我認為我做錯了,我不知道它是怎麼做到的完全有效。這是我的代碼
class Introduccion(Screen):
numbers = ObjectProperty()
number_list = ObjectProperty([])
def Add_ToList(self):
dat = self.numbers.text
self.number_list.append([dat])
和我的.kv文件
<Introduccion>:
numbers: numbers_input
number_list: number_list_view
RelativeLayout:
pos_hint:{'center_y': 0.8, 'center_x':0.5}
size_hint: None, None
size: 700, 200
pos: 200, 100
canvas.before:
Color:
rgba: 1, 0.1, 0.2, 0
Rectangle:
pos: 0,0
size: self.size
TextInput:
id: numbers_input
size_hint: None, None
pos: 520, 66
size: 70, 30
multiline: False
Button:
size_hint: None, None
pos: 600, 66
size: 50, 30
text: "añadir"
on_press: root.Add_ToList()
BoxLayout:
pos_hint:{'center_y': 0.8, 'center_x':0.5}
size_hint: None, None
size: 10, 10
pos: 200, 100
RecycleView:
id: number_list_view
viewclass: 'Label'
RecycleBoxLayout:
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
參考解法
方法 1:
The data
of a RecycleView
is a list of dictionaries with viewclass
attributes as keys and the value of that attribute as values. Since your viewclass
is Label
, an appropriate key in the data
dictionary is text
. So your Introduccion
class can be:
class Introduccion(Screen):
numbers = ObjectProperty()
number_list = ObjectProperty()
def Add_ToList(self):
self.number_list.data.append({'text': str(self.numbers.text)})
The Add_ToList()
method adds a new dictionary to the RecycleView
data
on each call. In each case, the key is text
(referring to the text
attribute of Label
), and the value is whatever is in the TextInput
.
(by juan sebastian、John Anderson)